package cn.lic.tool.poi.excel.function;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public abstract class IValue implements IFunctionArgument {
	
	public final static JSONArray EMPTY_ARRAY = new JSONArray();
	
	public enum Type {
		OBJECT,
		INT,
		FLOAT,
		STRING,
		BOOL,
		BIG_DECIMAL,
		JSON_OBJECT,
		JSON_ARRAY;
	}
	
	protected Object value;
	protected ContextWarp context;
	
	public static IValue buildSValue(Object val) {
		return new SValue(val);
	}
	public static IValue buildRValue(Object val) {
		return new RValue(val);
	}
	
	/**
	 * 使用给定的字符串表达式构建value对象:
	 * 如果字符串用单引号或双引号引用则为 svalue 字符串;
	 * 如果字符串为true或false则为 svalue boolean值;
	 * 如果字符串为int类型数字则为 svalue int值;
	 * 如果字符串为float类型数字则为 svalue float值;
	 * 其他情况为rvalue值.
	 * @param val
	 * @return
	 */
	public static IValue parse(String val) {
		if (val == null || val.length() == 0) {
			return new SValue(val);
		}
		try {
			Integer obj = Integer.parseInt(val);
			return new SValue(obj);
		} catch (Exception e) {
			
		}

		try {
			Float obj = Float.parseFloat(val);
			return new SValue(obj);
		} catch (Exception e) {
			
		}
		
		if ("true".equals(val) || "false".equals(val)) {
			return new SValue(Boolean.valueOf(val));
		}
		
		int ln = val.length();
		if (ln < 3) {
			return new RValue(val);
		}
		
		char start = val.charAt(0);
		char end = val.charAt(ln - 1);
		if ((start == '\'' && end == '\'') || start == '"' && end == '"') {
			return new SValue(val.substring(1, ln-1));
		}
		return new RValue(val);
	}
	
	public IValue setContext(JSONObject ctx) {
		this.context = new ContextWarp(ctx);
		return this;
	}
	
	abstract public boolean isNull();

	abstract public <T> T castValue(Type type);

	public <T> T castValue(Type type, T defVal) {
		T t = castValue(type);
		return t == null ? defVal : t;
	}

}
